<html>
<head>
  <title>聊天框</title>
</head>

<style>
  /*#chat {*/
  /*  text-align: left;*/
  /*  background: #f1f1f1;*/
  /*  width: 500px;*/
  /*  min-height: 300px;*/
  /*  padding: 20px;*/
  /*}*/
  /*div > p {*/
  /*  color: red;*/
  /*}*/
  #chat {
    text-align: left;
    background: #f1f1f1;
    width: 500px;
    min-height: 300px;
    padding: 20px;
    color: rgba(0,0,0,0.5);
  }

  /* 名字 */
  #chat > div > p{
    color: rgba(0,0,0,0.5);
    font-size:7px;
  }
  /*时间*/
  .chatTime {
    text-align:center;
  }

  .myMessage {
    float: right;
    display:inline-block;
    background-color: rgb(18, 183, 245);
    color: white;
    border-radius: 5px;
    padding: 5px;
    border: 1px solid rgb(229, 229, 229);
  }

  .noMyMessage {
    float: right;
    display:inline-block;
    background-color: #e5e5e5;
    color: black;
    border-radius: 5px;
    padding: 5px;
    border: 1px solid rgb(229, 229, 229);
  }
  #text {
    width: 500px;
    height: 20px;
    background-color: aquamarine;
    border: 1px solid rgba(196, 238, 241, 0.7);
    border-radius: 5px;
    padding-left: 10px;
  }
</style>

<body>
<center>
  <h3>Chat</h3>
  <div id="chat"></div>
  <input placeholder="回车发送" id="text" type="text">
</center>

<script>
  var name = "Guest" + Math.floor(Math.random() * 1000);
  // var name = {{ . }};
  var url = "ws://" + window.location.host + "/ws";
  var ws = new WebSocket(url);
  var chat = document.getElementById("chat");
  var text = document.getElementById("text");

  var now = function () {
    var iso = new Date().toISOString();
    return iso.split("T")[1].split(".")[0];
  };

  // 接收到消息后的回掉函数
  ws.onmessage = function (msg) {
    var div1Element = document.createElement("div")
    var timeElement = document.createElement("p")
    var nameElement = document.createElement("p")
    var textElement = document.createElement("div")
    // var line =  now() + "\n";
    timeElement.className = "chatTime"
    timeElement.innerHTML = now() + "<br />";
    // 名字
    nameElement.innerText =  msg.data.split("|")[0];
    // 数据
    textElement.className = name
    textElement.innerHTML = msg.data.split("|")[1] +"<br />";
    // 发送时会出现下一条消息样式消失的情况
    // chat.innerText += line;
    div1Element.appendChild(timeElement)
    div1Element.appendChild(nameElement);
    div1Element.appendChild(textElement)
    chat.appendChild(div1Element);
  };

  // 回车时发生信息
  text.onkeydown = function (e) {
    if (e.keyCode === 13 && text.value !== "") {
      ws.send(name + "|" + text.value);
      text.value = "";
    }
  };

  // 接收到消息后触发
  ws.addEventListener('message', function (event) {
    messages = document.querySelectorAll("#chat > div > div");
    console.log(messages)
    for (let i = 0; i < messages.length; i++) {
      if (messages[i].className === name) {
        messages[i].className = "myMessage"
      } else {
        messages[i].className = "noMyMessage"
      }
    }
  });

</script>
</body>
</html>